<template>
  <div class="flex flex-col h-full overflow-hidden">
    <app-header/>

    <main>
      <form @submit.prevent="saveEventConfig" id="event-config-form-alarm" class="config-form">
        <h2 class="form-title">事件配置 - Alarm</h2>

        <div class="form-section">
          <h3 class="form-section-title">基本设置</h3>
          <div class="form-group flex items-center gap-4 mb-3">
            <span class="toggle-label">启用此事件</span>
            <label class="switch">
              <input type="checkbox" id="alarm-enabled" v-model="eventConfig.enabled">
              <span class="slider" :class="{ 'checked': eventConfig.enabled }"></span>
            </label>
          </div>
          <p class="form-description mb-4">启用后，当设备发生未停机报警时，将触发此事件。</p>

          <div class="grid grid-cols-1 sm:grid-cols-2 gap-x-4 gap-y-2">
            <div class="form-group col-span-2">
              <label for="alarm-url" class="form-label">接收 URL <span class="text-red-500">*</span></label>
              <input type="url" id="alarm-url" v-model="eventConfig.url" class="form-input"
                     placeholder="例如: http://mes.example.com/api/alarm" required>
              <p class="form-description">MES 接收报警事件数据的 URL。</p>
            </div>

            <div class="form-group">
              <label for="alarm-line" class="form-label">产线 (Line) <span class="text-red-500">*</span></label>
              <input type="text" id="alarm-line" v-model="eventConfig.Line" class="form-input"
                     placeholder="例如: Y-FA-01" required>
              <p class="form-description">线别代码。</p>
            </div>
            <div class="form-group">
              <label for="alarm-stationid" class="form-label">站点 ID (StationID) <span
                class="text-red-500">*</span></label>
              <input type="text" id="alarm-stationid" v-model="eventConfig.StationID" class="form-input"
                     placeholder="例如: StatorWind" required>
              <p class="form-description">大机台段别，同MES Station。</p>
            </div>
            <div class="form-group">
              <label for="alarm-machineid" class="form-label">机台 ID (MachineID) <span
                class="text-red-500">*</span></label>
              <input type="text" id="alarm-machineid" v-model="eventConfig.MachineID" class="form-input"
                     placeholder="例如: WIND01" required>
              <p class="form-description">机台编号。</p>
            </div>
            <div class="form-group">
              <label for="alarm-opid" class="form-label">操作员 ID (OPID) <span class="text-red-500">*</span></label>
              <input type="text" id="alarm-opid" v-model="eventConfig.OPID" class="form-input"
                     placeholder="例如: HMIUser" required>
              <p class="form-description">操作人员ID，工号或UserID。</p>
            </div>
          </div>
        </div>

        <div class="button-group">
          <button type="button" id="btn-cancel-event-config" class="hmi-button hmi-button-secondary" @click="goBack">
            <i class="fas fa-times"></i>取消
          </button>
          <button type="submit" id="btn-save-event-config" class="hmi-button hmi-button-primary" :disabled="isSaving">
            <i :class="isSaving ? 'fas fa-spinner fa-spin' : 'fas fa-save'"></i>{{
              isSaving ? '保存中...' : '保存配置'
            }}
          </button>
        </div>
      </form>
    </main>

    <div v-if="notification.show" id="notification" class="notification"
         :class="{ 'notification-success': notification.type === 'success', 'notification-error': notification.type === 'error', 'show': notification.show }">
      <span id="notification-message">{{ notification.message }}</span>
    </div>
  </div>
</template>

<script setup>
import {ref, reactive, watch, onMounted, onUnmounted} from 'vue'
import {useRouter} from 'vue-router'
import {getMesEventConfig, saveMesEventConfig} from '@/api/mesEvent'

const eventName = 'Alarm'
const router = useRouter()
const isComponentMounted = ref(true)
const abortController = new AbortController()

// 状态变量
const isSaving = ref(false)

// 通知状态
const notification = reactive({
  show: false,
  message: '',
  type: 'success',
  timeoutId: null
})

// 事件配置
const eventConfig = reactive({
  "enabled": false,
  "url": '',
  "EventID": "ALARM",
  "Line": "",
  "StationID": "",
  "MachineID": "",
  "OPID": ""
  // Alarm 事件不需要 Token、FixSN 和 heartbeat_interval
})

// 显示通知
const showNotification = (message, type = 'success') => {
  if (notification.timeoutId) {
    clearTimeout(notification.timeoutId)
  }

  notification.message = message
  notification.type = type
  notification.show = true

  notification.timeoutId = setTimeout(() => {
    notification.show = false
  }, 3000)
}

// 返回上一页
const goBack = () => {
  router.back()
}

// 保存配置
const saveEventConfig = async () => {
  const form = document.getElementById('event-config-form-alarm')
  // 使用 Vue 的 $refs 或获取DOM元素进行验证
  if (!form || !form.checkValidity()) {
    showNotification('请填写所有必填项 (*)', 'error')
    // 触发表单的原生验证提示
    if (form) form.reportValidity()
    return
  }

  isSaving.value = true
  // 实现保存逻辑
  console.log('saveEventConfig', eventConfig)
  const dataToSave = JSON.parse(JSON.stringify(eventConfig))
  try {
    await saveMesEventConfig(eventName, dataToSave)
    showNotification('Alarm 配置保存成功!', 'success')
    goBack()
  } catch (error) {
    console.error('保存配置失败:', error)
    showNotification(`保存失败: ${error.message || '未知错误'}`, 'error')
  } finally {
    isSaving.value = false
  }
}

// 加载配置
const loadConfig = async () => {
  if (!isComponentMounted.value) return

  try {
    const config = await getMesEventConfig(eventName, abortController.signal)
    if (!isComponentMounted.value) return

    if (config) {
      Object.assign(eventConfig, config)
    } else {
      // 使用默认配置
      const defaultConfig = {
        enabled: false,
        url: '',
        EventID: "ALARM",
        Line: "",
        StationID: "",
        MachineID: "",
        OPID: ""
      }
      Object.assign(eventConfig, defaultConfig)
    }
  } catch (error) {
    if (error.name === 'AbortError') return
    console.error('加载配置失败:', error)
    showNotification('加载配置失败: ' + error.message, 'error')
  }
}

// 处理ESC键返回
const handleEscape = (event) => {
  if (event.key === 'Escape') {
    goBack()
  }
}

// 生命周期钩子
onMounted(async () => {
  isComponentMounted.value = true
  document.addEventListener('keydown', handleEscape)
  await loadConfig()
})

onUnmounted(() => {
  isComponentMounted.value = false
  abortController.abort()
  document.removeEventListener('keydown', handleEscape)
  if (notification.timeoutId) {
    clearTimeout(notification.timeoutId)
  }
})

</script>

<style scoped>
/* --- 将原始 HTML 文件中的所有自定义样式复制到这里 --- */

/* --- Inherited Styles & Color Palette --- */
/* 根变量通常在全局 CSS 中定义，但为了完整性，这里列出 */
/* :root {
  --bg-primary: #f3f4f6;
  --bg-secondary: #ffffff;
  --text-primary: #1f2937;
  --text-secondary: #6b7280;
  --text-tertiary: #9ca3af;
  --border-color: #e5e7eb;
  --accent-blue: #3b82f6;
  --status-green: #22c55e;
  --status-yellow: #eab308;
  --status-red: #ef4444;
  --status-gray: #6b7280;
  --status-off: #9ca3af;
  --online-green: #10b981;
  --offline-red: #f43f5e;
} */

/* body 样式通常由父组件或全局 App.vue 控制 */
/* body {
  font-family: 'Inter', 'Helvetica Neue', Helvetica, Arial, sans-serif;
  background-color: var(--bg-primary);
  color: var(--text-primary);
  display: flex;
  flex-direction: column;
  height: 100vh;
  overflow: hidden;
} */

/* --- Header (Consistent) --- */
/* Header 样式已移至 AppHeader.vue 或全局 */


/* --- Main Content Area --- */
main {
  flex-grow: 1;
  padding: 1.5rem;
  overflow-y: auto; /* Enable scrolling for form */
}

/* --- Configuration Form --- */
.config-form {
  background-color: var(--bg-secondary);
  border-radius: 0.75rem;
  box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.05), 0 2px 4px -2px rgba(0, 0, 0, 0.05);
  padding: 1.5rem;
  border: 1px solid var(--border-color);
  max-width: 900px; /* Adjust max width for this form */
  margin: 0 auto; /* Center form */
}

.form-title {
  font-size: 1.1rem;
  font-weight: 700;
  color: var(--text-primary);
  margin-bottom: 1.5rem;
  text-align: center;
  border-bottom: 1px solid var(--border-color);
  padding-bottom: 0.75rem;
}

.form-section {
  margin-bottom: 1.5rem;
}

.form-section-title {
  font-size: 0.9rem;
  font-weight: 600;
  color: var(--text-primary);
  margin-bottom: 0.75rem;
  border-left: 3px solid var(--accent-blue);
  padding-left: 0.5rem;
}

.form-group {
  margin-bottom: 1rem;
}

.form-label {
  display: block;
  font-size: 0.8rem;
  font-weight: 500;
  color: var(--text-secondary);
  margin-bottom: 0.25rem;
}

.form-input, .form-select {
  width: 100%;
  padding: 0.5rem 0.75rem;
  border: 1px solid var(--border-color);
  border-radius: 0.5rem;
  font-size: 0.875rem;
  transition: border-color 0.2s ease, box-shadow 0.2s ease;
  background-color: #f9fafb;
}

.form-input:focus, .form-select:focus {
  outline: none;
  border-color: var(--accent-blue);
  box-shadow: 0 0 0 2px rgba(59, 130, 246, 0.3);
  background-color: white;
}

.form-input:required:invalid, .form-select:required:invalid {
  border-color: var(--status-red);
}

.form-input[readonly] {
  background-color: #e5e7eb;
  cursor: not-allowed;
  opacity: 0.7;
  color: var(--text-secondary);
}

.form-select {
  appearance: none;
  background-image: url("data:image/svg+xml,%3csvg xmlns='http://www.w3.org/2000/svg' fill='none' viewBox='0 0 20 20'%3e%3cpath stroke='%236b7280' stroke-linecap='round' stroke-linejoin='round' stroke-width='1.5' d='M6 8l4 4 4-4'/%3e%3csvg%3e");
  background-position: right 0.5rem center;
  background-repeat: no-repeat;
  background-size: 1.5em 1.5em;
  padding-right: 2.5rem;
}

.form-description {
  font-size: 0.7rem;
  color: var(--text-tertiary);
  margin-top: 0.25rem;
}

/* Input group for select + button (if any) */
.input-button-group {
  display: flex;
  gap: 0.5rem;
  align-items: center;
}

.input-button-group .form-select {
  flex-grow: 1;
}

.input-button-group .hmi-button {
  flex-shrink: 0;
}


/* Toggle Switch */
.toggle-switch {
  display: flex;
  align-items: center;
  gap: 1rem;
}

.toggle-label {
  font-size: 0.8rem;
  font-weight: 500;
  color: var(--text-secondary);
  flex-shrink: 0;
}

.switch {
  position: relative;
  display: inline-block;
  width: 40px;
  height: 20px;
  flex-shrink: 0;
}

.switch input {
  opacity: 0;
  width: 0;
  height: 0;
}

.slider {
  position: absolute;
  cursor: pointer;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: #ccc;
  transition: .4s;
  border-radius: 20px;
}

.slider:before {
  position: absolute;
  content: "";
  height: 14px;
  width: 14px;
  left: 3px;
  bottom: 3px;
  background-color: white;
  transition: .4s;
  border-radius: 50%;
}

/* Apply background color based on checked state in Vue with binding */
.slider.checked {
  background-color: var(--accent-blue);
}

/* Apply transform based on checked state in Vue with binding */
input:checked + .slider:before {
  transform: translateX(20px);
}


/* --- Buttons --- */
.button-group {
  display: flex;
  gap: 1rem;
  justify-content: flex-end;
  margin-top: 2rem;
  border-top: 1px solid var(--border-color);
  padding-top: 1.5rem;
}

.hmi-button {
  padding: 0.6rem 1.2rem;
  border-radius: 0.5rem;
  font-size: 0.875rem;
  font-weight: 600;
  display: inline-flex;
  align-items: center;
  justify-content: center;
  gap: 0.4rem;
  border: 1px solid transparent;
  transition: all 0.2s ease;
  cursor: pointer;
}

/* Adjusted padding for small button */
.hmi-button-small {
  padding: 0.35rem 0.7rem;
  font-size: 0.75rem;
}

.hmi-button i {
  font-size: 1em;
}

/* HMI Button Colors - Defined by variables */
.hmi-button-primary {
  background-color: var(--accent-blue);
  color: white;
  border-color: var(--accent-blue);
}

.hmi-button-primary:hover {
  background-color: #2563eb;
  border-color: #2563eb;
}

/* Specific hover color */
.hmi-button-secondary {
  background-color: var(--bg-secondary);
  color: var(--text-primary);
  border-color: var(--border-color);
}

.hmi-button-secondary:hover {
  background-color: #f9fafb;
  border-color: #d1d5db;
}

/* Specific hover color */
.hmi-button:disabled {
  opacity: 0.5;
  cursor: not-allowed;
}

/* --- Notification --- */
.notification {
  position: fixed;
  bottom: 1rem;
  left: 50%;
  transform: translateX(-50%);
  padding: 0.75rem 1.25rem;
  border-radius: 0.5rem;
  color: white;
  font-size: 0.875rem;
  font-weight: 500;
  box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
  opacity: 0;
  visibility: hidden;
  transition: opacity 0.3s ease, visibility 0.3s ease;
  z-index: 100;
}

.notification.show {
  opacity: 1;
  visibility: visible;
}

/* Notification Colors - Defined by variables */
.notification-success {
  background-color: var(--status-green);
}

.notification-error {
  background-color: var(--status-red);
}


/* Body styles from original inline style */
/* max-width: 800px; max-height: 600px; margin: auto; */
/* These should ideally be managed in a layout component or App.vue */

</style>
